package leeon.bbsbrower.actions;

import ipworks.IPWorksException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import leeon.bbsbrower.BBSBrowerPlugin;
import leeon.bbsbrower.models.BoardObject;
import leeon.bbsbrower.util.HTMLUtil;
import leeon.bbsbrower.util.HTTPBean;
import leeon.bbsbrower.util.XmlOperator;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class BBSBoardAction {
	
	
	//获取所有版面和我的版面的地址
	public static final String URL_MY_AND_ALL_BOARD = Config.SERVER_URL + Config.SERVER_CGI + "bbsmybrd";
	
	//获取某个讨论块下的版面
	public static final String URL_BOARD_OF_ONE_BLOCK = Config.SERVER_URL + Config.SERVER_CGI + "bbsboa";
	
	//获取收藏的路径
	public static final String PATH_MY_BOARD = "conf/myboard.xml";
	
	
	//所有版面单例
	private static BoardObject[] boards = null;
	
	//我的版面单例
	private static BoardObject[] myboards = null;
	
	//分类版面的单例
	private static Map<String, BoardObject[]> map = new HashMap<String, BoardObject[]>();
	
	
	
	/**
	 * 获取所有版面
	 * @throws IPWorksException 
	 */
	public static BoardObject[] getAllBoards() throws IPWorksException {
		if (boards == null) {			
			HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
			String content = http.get(URL_MY_AND_ALL_BOARD);
			content = HTMLUtil.findStr(content, "<table>", "</table>");
			if (content != null) {
				String[] contents = HTMLUtil.findStrs(content, "<td>", "</td>");
				
				ArrayList<BoardObject> list = new ArrayList<BoardObject>();
				if (contents != null) {
					for (int i = 0; i < contents.length; i ++) {
						String[] cells = dealMyBoardTitle(contents[i]);
						
						BoardObject b = new BoardObject(
							String.valueOf(i),
							cells[0],
							null,
							cells[1],
							null,
							null,
							null,
							cells[2]
						);
						list.add(b);
					}
				}
				if (list.size() != 0)
					boards = list.toArray(new BoardObject[0]);
			}
		}
		return boards;
			
//			for (int i = 0; i < list.size(); i ++) {
//				BoardObject b = (BoardObject)list.get(i);
//				System.out.println(b.getNumber() + " " + b.getName() + " " + b.getType() + " " + b.getMaster() + " " + b.getCh() + " " + b.getDocNumber()+ " " + b.getURL());
//			}

	}
	
	private static String[] dealMyBoardTitle(String source) {
		if (source != null) {
			String[] re = new String[3];
			//name
			re[0] = HTMLUtil.findStr(source, "name=", " ");
			
			//ch
			re[1] = HTMLUtil.findStr(source, ">", "</a>");
			if (re[1] != null) re[1] = HTMLUtil.removeHtmlTag(re[1]);
			
			//href
			re[2] = Config.SERVER_URL + Config.SERVER_CGI + HTMLUtil.findStr(source, "href=", ">");
			
			return re;
		
		} else
			return null;
	}
	
	
	/**
	 * 删除版面
	 * @param name
	 */
	public static void rmMyBoard(String name) {
		try {
			Document doc = XmlOperator.createXmlDocument(BBSBrowerPlugin.getRealFile(PATH_MY_BOARD), "boards");		
			if (doc != null) {
				NodeList bs = doc.getElementsByTagName("board");
				for (int i = 0; i < bs.getLength(); i++) {
					Node b = bs.item(i);
					if (b.getNodeType() == Node.ELEMENT_NODE) {
						if (name.equals(((Element) b).getAttribute("name"))) {
							b.getParentNode().removeChild(b);
							XmlOperator.saveDocument(BBSBrowerPlugin.getRealFile(PATH_MY_BOARD), doc);
							
							myboards = null;
							getMyBoards();
							return;
						}
					}
				}
			}			
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	
	/**
	 * 添加版面
	 * @param name
	 */
	public static void addMyBoard(String name, String ch) {
		try {
			Document doc = XmlOperator.createXmlDocument(BBSBrowerPlugin.getRealFile(PATH_MY_BOARD), "boards");		
			if (doc != null) {
				Element b = doc.createElement("board");
				b.setAttribute("name", name);
				b.setAttribute("ch", ch);
				doc.getElementsByTagName("boards").item(0).appendChild(b);
				XmlOperator.saveDocument(BBSBrowerPlugin.getRealFile(PATH_MY_BOARD), doc);
				
				myboards = null;
				getMyBoards();
			}			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * 获取我的版面
	 */
	public static BoardObject[] getMyBoardsFromURL() {
		if (myboards != null) return myboards;
		
		ArrayList<BoardObject> list = new ArrayList<BoardObject>();
		try {
			HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
			String content = http.get(BBSBlockAction.URL_BLOCK);
			
			String board = HTMLUtil.findStr(content, "预定管理\n</a>", "</a>\n</div>");
			String[] bs = board.split("</a>"); 
			
			for (int i = 0; i < bs.length; i++) {
				String name = HTMLUtil.findStr(bs[i], "target=\"view\">").trim();
				BoardObject bo = new BoardObject(
						String.valueOf(i),
						name,
						null,
						name,
						null,
						null,
						null,
						(BBSLogAction.t == 1)?
						BBSDocAction.URL_DOC_FROM_ONE_BOARD_T + "?board=" + name:
						BBSDocAction.URL_DOC_FROM_ONE_BOARD + "?board=" + name
				);
				list.add(bo);
			}
			
		} catch (IPWorksException e) {
			e.printStackTrace();
		}
		
		myboards = list.toArray(new BoardObject[0]);
		return myboards;
	}
	
	
	/**
	 * 获取我的版面
	 */
	public static BoardObject[] getMyBoards() {
		if (myboards == null) {
			Document doc = null;
			try {
				doc = XmlOperator.readDocument(BBSBrowerPlugin.getRealFile(PATH_MY_BOARD));
			} catch (IOException e) {
				e.printStackTrace();
			}
						
			if (doc != null) {
				ArrayList<BoardObject> list = new ArrayList<BoardObject>();
				NodeList bs = doc.getElementsByTagName("board");
				for (int i = 0; i < bs.getLength(); i++) {
					Node b = bs.item(i);
					if (b.getNodeType() == Node.ELEMENT_NODE) {
						String name = ((Element) b).getAttribute("name");
						String ch = ((Element) b).getAttribute("ch");
						BoardObject bo = new BoardObject(
								String.valueOf(i),
								name,
								null,
								ch,
								null,
								null,
								null,
								(BBSLogAction.t == 1)?
								BBSDocAction.URL_DOC_FROM_ONE_BOARD_T + "?board=" + name:
								BBSDocAction.URL_DOC_FROM_ONE_BOARD + "?board=" + name
						);
						list.add(bo);
					}
				}
				if (list.size() != 0)
					myboards = list.toArray(new BoardObject[0]);
			}
		}
		return myboards;
	}
	
	
	/**
	 * 通过url获取分类讨论快下的版面
	 * @param url
	 * @throws IPWorksException 
	 */
	public static BoardObject[] getBoardsOfBlockByURL(String url) throws IPWorksException {
		if (map.get(url) == null) {
			
			HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
			String content = http.get(url);
			content = HTMLUtil.findStr(content, "<table width=100% bgcolor=#ffffff>", "</table>");
			String[] rows = HTMLUtil.dealTableRows(content);
			
			ArrayList<BoardObject> list = new ArrayList<BoardObject>();
			if (rows.length > 1) {
				for (int i = 1; i < rows.length; i ++) {
					String[] cells = HTMLUtil.dealTableCells(rows[i]);
					
					BoardObject b = new BoardObject(
						cells[0],
						HTMLUtil.removeHtmlTag(cells[2]).trim(),
						cells[4],
						HTMLUtil.findStr(cells[5], "<b> ", "</b>"),
						HTMLUtil.removeHtmlTag(cells[6]).trim(),
						cells[7].trim(),
						cells[1] + " " + cells[3],
						Config.SERVER_URL + Config.SERVER_CGI + HTMLUtil.findStr(cells[2], "href=", ">")
					);
					list.add(b);
				}
			}
			if (list.size() != 0) {
				BoardObject[] bs = list.toArray(new BoardObject[0]);
				map.put(url, bs);
			}
		}
			
		return map.get(url);
	}
	
	/**
	 * 通过分类讨论块的编号获取该块下的所有版面
	 * @param no
	 * @throws IPWorksException 
	 */
	public static BoardObject[] getBoardsOfBlockByNo(String no) throws IPWorksException {
		return getBoardsOfBlockByURL(URL_BOARD_OF_ONE_BLOCK + "?" + no);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	}

}
